package com.geekhalo.info.app.categorystatis;

import com.geekhalo.info.domain.categorystatis.Incr.IncrCountOfInfoByCategoryCommand;
import com.geekhalo.info.domain.info.picture.create.PictureInfoCreatedEvent;
import com.geekhalo.info.domain.info.text.create.TextInfoCreatedEvent;
import com.geekhalo.info.domain.info.video.create.VideoInfoCreatedEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.event.TransactionalEventListener;

@Service
@Async
@Slf4j
public class CountSyncListener {
    @Autowired
    private CountOfInfoByCategoryCommandApplication commandApplication;

    @TransactionalEventListener
//    @Async
    public void handle(TextInfoCreatedEvent event){
        increase(event.getSource().getCategoryId(), 1);
    }

    @TransactionalEventListener
//    @Async
    public void handle(PictureInfoCreatedEvent event){
        increase(event.getSource().getCategoryId(), 1);
    }

    @TransactionalEventListener
//    @Async
    public void handle(VideoInfoCreatedEvent event){
        increase(event.getSource().getCategoryId(), 1);
    }

    private void increase(Long categoryId, int count) {
        log.info("Increase category {} by {}", categoryId, count);
        IncrCountOfInfoByCategoryCommand command = new IncrCountOfInfoByCategoryCommand();
        command.setKey(categoryId);
        command.setCount(count);
        this.commandApplication.incr(command);
    }

}
